//
//  SysDict.m
//  XPhoto
//
//  Created by sentinel on 2020/4/13.
//  Copyright © 2020 baboy. All rights reserved.
//

#import "SysDict.h"
#import <BKKit/BKApi.h>
#import <BKKit/HttpResponse.h>
#import <BKKit/Mem.h>

#define SYS_DICT_MEM_KEY        @"sys_dict"

@implementation SysDictItem
@end

@implementation SysDict
+ (NSURL *)cacheURL{
    NSString *fp = getStorageFilePath(@"sys_dict.plist", nil);
    NSURL *fileURL = [NSURL fileURLWithPath:fp];
    return fileURL;
}
+ (void)saveCache:(NSDictionary *)data{
    BOOL flag = [data writeToURL:[self cacheURL] atomically:YES];
    DLOG(@"saveCache:%d", flag);
}
+ (void)initialize{
    NSDictionary *data = [NSDictionary dictionaryWithContentsOfURL:[self cacheURL]];
    if (!data) {
        return;
    }
    HttpResponse *response = [HttpResponse responseWithDictionary:data dataItemClass:[SysDict class]];
    if ([response isSuccess]) {
        [self loadSysDictToMem:response.data];
    }
}
+ (void)loadSysDictToMem:(NSArray *)array{
    if (!array) {
        return;
    }
    NSMutableDictionary *data = [Mem valueForKey:SYS_DICT_MEM_KEY];
    if (!data) {
        data = [NSMutableDictionary dictionary];
        [Mem setValue:data forKey:SYS_DICT_MEM_KEY];
    }
    for (SysDict *d in array) {
        [data setValue:d forKey:d.key];
    }
}
+ (SysDict *)dictForKey:(NSString *)key{
    NSDictionary *data = [Mem valueForKey:SYS_DICT_MEM_KEY];
    return [data valueForKey:key];
}
+ (SysDictItem *)itemForValue:(NSString *)val dictKey:(NSString *)dictKey{
    SysDict *dict = [self dictForKey:dictKey];
    if (!dict || !dict.items) {
        return nil;
    }
    for (SysDictItem *item in dict.items) {
        if ([item.value isEqualToString:val]) {
            return item;
        }
    }
    return nil;
}
+ (SysDictItem *)itemForKey:(NSString *)key dictKey:(NSString *)dictKey{
    SysDict *dict = [self dictForKey:dictKey];
       if (!dict || !dict.items) {
           return nil;
       }
       for (SysDictItem *item in dict.items) {
           if ([item.key isEqualToString:key]) {
               return item;
           }
       }
       return nil;
}
+ (void)loadSysDict{
     [BKApi request:API_DICT_SEARCH
         parameters:nil
           callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
               if (!error) {
                   HttpResponse *response = [HttpResponse responseWithDictionary:json dataItemClass:[SysDict class]];
                   if ([response isSuccess]) {
                       [self loadSysDictToMem:response.data];
                       [self saveCache:json];
                       [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CONFIG_FINISHED object:nil];
                   }
               }
           }];
}
@end
